package com.study;

import cn.hutool.core.date.DateUtil;
import com.influxdb.client.*;
import com.influxdb.client.domain.Query;
import com.influxdb.client.domain.QueryVariableProperties;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.study.pojo.CentreIotData;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * @Description: TODO
 * @Author: csc
 * @Date: 2024/4/11 14:22
 * @Version: 1.0
 **/
public class test {

    private static char[] token = "oLpHiTew0eh9JtzdbmQLXFxKC4cuJvpfzn_NOiqR4fzhYWLmOci5c99YT5_6tILmYDTAYbDF4F7Vp1vl6jVJKw==".toCharArray();

    private static String org = "xyyl";

    /**存储桶的名称*/
    private static String bucket = "smqtt";

    private static String url = "http://192.168.112.129:8086/";

    public static void main(String[] args) {

        InfluxDBClient influxDBClient = InfluxDBClientFactory.create(url, token, org, bucket);
        WriteApiBlocking writeApiBlocking = influxDBClient.getWriteApiBlocking();
        WriteApi writeApi = influxDBClient.makeWriteApi();


        QueryApi queryApi = influxDBClient.getQueryApi();

        //常用偏移，得到当前时间的前12个小时
        Date newDate2 = DateUtil.offsetHour(new Date(), -12);

        String flux = createFluxQuery(newDate2,new Date(),1,100);


        List<CentreIotData> query = queryApi.query(flux, CentreIotData.class);
        query.forEach(System.out::println);

    }

    private static String createFluxQuery(Date start, Date end, int pageNumber, int pageSize) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

        String startTime = DateUtil.format(start,"yyyy-MM-dd'T'HH:mm:ss'Z'");
        String endTime = DateUtil.format(end,"yyyy-MM-dd'T'HH:mm:ss'Z'");

        return String.format(
                "from(bucket: \"%s\")\n" +
                        " |> range(start: %s, stop: %s)\n" +
                        " |> filter(fn: (r) => r[\"_measurement\"] == \"centreIotData\")\n" +
                        " |> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")\n" +
                        " |> limit(n: %d, offset: %d)\n" +
                        " |> yield(name: \"mean\")",
                bucket, startTime, endTime, pageSize, (pageNumber - 1) * pageSize
        );
    }

}
